package com.squirrelhuan.quickhttp_sample;

import android.util.Log;



import java.io.IOException;
import java.nio.charset.Charset;

import io.reactivex.annotations.NonNull;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

public class QuickHttpLoggingInterceptor implements Interceptor {
    String TAG = QuickHttpLoggingInterceptor.class.getSimpleName();
    @NonNull
    @Override
    public Response intercept(@NonNull Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        Log.d(TAG,String.format("Sending request %s on %s%n%s",
                request.url(), chain.connection(), request.headers()));

        Response response = chain.proceed(request);

        long t2 = System.nanoTime();
        Log.d(TAG,String.format("Received response for %s in %.1fms%n%s",
                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        
        // 打印响应体（如果需要的话，注意大响应体可能会消耗大量内存）
        ResponseBody responseBody = response.body();
        BufferedSource source = responseBody.source();
        source.request(Long.MAX_VALUE); // Buffer the entire body.
        Buffer buffer = source.buffer();

        String bodyString = buffer.clone().readString(Charset.forName("UTF-8"));
        Log.d(TAG,"Response Body: " + bodyString);

        return response;
    }
}
